const puppeteer = require('puppeteer');
const { loginUrl, cartUrl, goodsList, delayTimes } = require("./config");
const { $formatDate } = require("./utils");
const child_process = require('child_process')
async function _start() {
  const launchOpts = {
    headless: process.env.NODE_ENV === "development" ? false : true
    , args: [`--window-size=1920,900`]
    , defaultViewport: { width: 1920, height: 900 }
    , executablePath: 'C:/Chromium/chrome-win/chrome.exe',
  };
  const browser = await puppeteer.launch(launchOpts);
  const page = (await browser.pages())[0];
  // 登录验证
  await page.goto(loginUrl);
  // 点击展开二维码
  await page.click(".icon-qrcode");
  // 保存二维码到本地 
  const verifyImg = await page.waitForSelector('.login-content');
  const verifyName = new Date().getTime() + "verify.png";

  setTimeout(async () => {
    await verifyImg.screenshot({
      path: verifyName,
      omitBackground: false
    });
    await child_process.exec(verifyName);

    // 等待登录状态后 重定向
    await page.waitForNavigation({ timeout: 100000, waitUntil: "domcontentloaded" });

    // 对商品列表分窗
    const goodsLength = goodsList.length;
    const intervalTime = 50;

    async function _waitPages(goodsItem) {
      const goodsItemPage = await browser.newPage();
      await goodsItemPage.goto(cartUrl);
      const { seletorId, endDateStr } = goodsItem;
      let goodsSeletor;
      try {
        goodsSeletor = await goodsItemPage.$(`[for='${seletorId}']`);
      } catch (err) {
        console.warn(`商品-${seletorId} 购物车未找到元素，请抓紧核实！`);
      }
      await goodsSeletor.click();
      let settleHandleEle = await goodsItemPage.$("#J_Go");
      const endDateTimes = new Date(endDateStr).getTime() - (delayTimes || 0);
      // 对下一步浏览器进程 成功-进入提交订单页面   失败-被拦截或其他情况  进行静态资源拦截
      await goodsItemPage.setRequestInterception(true);
      await goodsItemPage.on('request', interceptedRequest => {
        const url = interceptedRequest.url()
        //判断如果是 图片请求  就直接拦截  
        if (url.endsWith('.png')
          || url.endsWith('.jpg')
          || url.endsWith('.gif')
          || url.endsWith('.css')
          || url.endsWith('.webp')
        ) {
          interceptedRequest.abort();   //终止请求
        }
        else {
          interceptedRequest.continue();//弹出}
        }
      });
      // 开启定时器
      let killInterval = setInterval(async function () {
        const curDateTimes = new Date().getTime();
        // 计时对比
        if (curDateTimes >= endDateTimes) {
          clearInterval(killInterval);
          killInterval = null;
          // 执行结算事件
          await settleHandleEle.click();
          // 等待页面重定向
          // console.log($formatDate(new Date()).format);
          await goodsItemPage.waitForNavigation({ timeout: 100000, waitUntil: "domcontentloaded" });
          // console.log("加载完成",$formatDate(new Date()).format);

          // 单次执行  提交订单事件
          await goodsItemPage.click(".go-btn")
            .then(function () {
              // 如果成功打印 提交订单成功
              const { format } = $formatDate(new Date());
              console.log(seletorId + " 提交订单成功! time at " + format);
              //等待付款重定向
              return goodsItemPage.waitForNavigation({ timeout: 1500, waitUntil: "domcontentloaded" });
            }).then(function () {
              const { format } = $formatDate(new Date());
              console.log(seletorId + " 抢购成功! time at " + format);
            }).catch(function () {
              // 如果失败 提交订单失败
              const { format } = $formatDate(new Date());
              console.log(seletorId + " 提交订单失败! time at " + format);

            });
          //对结果进行截图  并打开这个截图
          const resultImgName = seletorId + "-result.png";
          await goodsItemPage.screenshot({
            path: resultImgName
          });
          child_process.exec(resultImgName);
          /* 
          //   多次点击提交订单
          const submitHandleEle = await  goodsItemPage.$(".go-btn");
          let maxSubmitNumber = 5;
          let submitSpace = 0;
          let iterSubmitCount = 0;
          let submitInterval = setInterval(async function(){
            submitHandleEle.click()
            .then( async function(){
              await goodsItemPage.waitForNavigation({ timeout: 100000, waitUntil: "domcontentloaded" });
              const { format } = $formatDate(new Date());
              console.log(seletorId + " 抢购成功! time at " + format);
            })
            .catch(function(err){
              clearInterval( submitInterval );
              const { format } = $formatDate(new Date());
              console.log(seletorId + " 抢购失败! time at " + format);
            });
            iterSubmitCount ++;
            if( iterSubmitCount >= maxSubmitNumber){
              clearInterval( submitInterval );
            }
          },submitSpace); */


        }
      }, intervalTime);
    }
    if (goodsLength) {
      const notic = goodsLength === 1
        ? "当前只有一个商品，不进行分窗"
        : "多窗口模式启动";
      console.log(notic);
      goodsList.forEach(async function (goodsItem) {
        _waitPages(goodsItem);
      });
    } else {
      console.error("请重新配置商品列表")
    }
  }, 800);

}
_start();

